//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package atomgit_triger

import (
	"encoding/json"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/triger_impl/core"
)

type PullRepoInfo struct {
	CloneUrl string `json:"clone_url"`
	SshUrl   string `json:"ssh_url"`
	HtmlUrl  string `json:"html_url"`
}

type PullBaseInfo struct {
	Ref  string       `json:"ref"`
	Repo PullRepoInfo `json:"repo"`
}

type PullHeadInfo struct {
	Ref  string       `json:"ref"`
	Repo PullRepoInfo `json:"repo"`
}

type PullRequestInfo struct {
	CreatedAt string       `json:"created_at"`
	UpdatedAt string       `json:"updated_at"`
	Title     string       `json:"title"`
	PullBase  PullBaseInfo `json:"base"` //target
	PullHead  PullHeadInfo `json:"head"` //source
}

type PrHookInfo struct {
	Number      int             `json:"number"`
	PullRequest PullRequestInfo `json:"pull_request"`
}

func ExtractPrHookAttr(data []byte) ([]string, error) {
	obj := &PrHookInfo{}

	err := json.Unmarshal(data, obj)
	if err != nil {
		return nil, err
	}

	retList := []string{
		fmt.Sprintf("%s=%s", core.GIT_HOOK_TYPE, "pr"),
		fmt.Sprintf("%s=%d", core.GIT_PR_ID, obj.Number),
		fmt.Sprintf("%s=%s", core.GIT_PR_CREATE_AT, obj.PullRequest.CreatedAt),
		fmt.Sprintf("%s=%s", core.GIT_PR_UPDATE_AT, obj.PullRequest.UpdatedAt),
		fmt.Sprintf("%s=%s", core.GIT_PR_TITLE, obj.PullRequest.Title),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_BRANCH, obj.PullRequest.PullHead.Ref),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_WEB_URL, obj.PullRequest.PullHead.Repo.HtmlUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_HTTP_URL, obj.PullRequest.PullHead.Repo.CloneUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_SSH_URL, obj.PullRequest.PullHead.Repo.SshUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_BRANCH, obj.PullRequest.PullBase.Ref),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_WEB_URL, obj.PullRequest.PullBase.Repo.HtmlUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_HTTP_URL, obj.PullRequest.PullBase.Repo.CloneUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_SSH_URL, obj.PullRequest.PullBase.Repo.SshUrl),
	}
	return retList, nil
}
